//
//  ViewController.swift
//  WQWebData
//
//  Created by huwenqiang on 2019/11/25.
//  Copyright © 2019 huwenqiang. All rights reserved.
//

import UIKit
import CSV
import Alamofire
import SnapKit

class ViewController: UIViewController {
    
    var dataArray:[WQFavorites] = []
    
    var favorites_id = ""
    var category = ""
    
    lazy var buttonConfirm = { () -> UIButton in
        let button = UIButton.init()
        button.backgroundColor = .purple
        button.layer.cornerRadius = 4
        button.setTitle("OutPut", for: .normal)
        button.addTarget(self, action: #selector(requestAndWriteToFile), for: .touchUpInside)
        return button
    }()
    
    lazy var mtextField = { () -> UITextField in
        let textField = UITextField.init()
        textField.backgroundColor = UIColor.init(white: 0.2, alpha: 1)
        textField.placeholder = "Please input category"
        textField.font = UIFont.systemFont(ofSize: 14)
        textField.layer.cornerRadius = 4
        return textField
    }()
    
    static func pushToController(nav:UINavigationController?, category:String, favorites_id:String) {
        let vc = ViewController.init()
        vc.category = category
        vc.favorites_id = favorites_id
        nav?.pushViewController(vc, animated: true)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        
        self.initViews()
        self.fillViewDatas()
        
    }
    
    func initViews() {
        
        self.view.addSubview(self.mtextField)
        self.mtextField.snp.makeConstraints { (make) in
            make.height.equalTo(33)
            make.leading.equalTo(self.view).offset(16)
            make.centerX.equalTo(self.view)
            make.top.equalTo(self.view).offset(16)
        }
        
        self.view.addSubview(self.buttonConfirm)
        self.buttonConfirm.snp.makeConstraints { (make) in
            make.leading.trailing.equalTo(self.mtextField)
            make.height.equalTo(44)
            make.top.equalTo(self.mtextField.snp.bottom).offset(16)
        }
    }
    
    func fillViewDatas()  {
        self.mtextField.text = self.category
    }
    
    @objc func requestAndWriteToFile() {
        if self.favorites_id == "" {
            print("favorites_id 为空")
            return
        }
        WQRequestHelper.request(param: ["page_no":"1","page_size":"200","platform":"2","favorites_id":self.favorites_id,"fields":"num_iid,title,pict_url,small_images,reserve_price,zk_final_price,user_type,item_url,volume,shop_title,zk_final_price_wap,tk_rate,status,type,click_url,coupon_click_url,coupon_info,coupon_remain_count,category,coupon_end_time,coupon_start_time","adzone_id":Adzone_id_6shitu], method: .get, apiName: request_api_uatm_favorites_item, succeed: { (data) in
            let temp = data as! [String:Any]
            let model = WQBaseModel.deserialize(from: temp, designatedPath: "tbk_uatm_favorites_item_get_response.results")
            let array = model?.uatm_tbk_item
            if array != nil {
                self.dataArray = array!
                print("remove之前\(self.dataArray.count)")
                var temp:[WQFavorites] = []
                for item in self.dataArray {
                    if item.coupon_remain_count > 50 {
                        temp.append(item)
                    }
                }
                self.dataArray = temp
                print("remove之后\(self.dataArray.count)")
                for (index,item) in self.dataArray.enumerated() {
                    self.requestDetailTB(index: index, item: item)
                }
            }
        }) { (error) in
            
        }
    }
    
    func requestDetailTB(index:Int, item:WQFavorites) {
        let dataItem = self.dataArray[index]
        WQRequestHelper.requestGoodDetailTB(goodId: item.num_iid, method: .get, succeed: { (data) in
            let temp = data as! [String:Any]
            let favOther = WQFavoritesOther.deserialize(from: temp, designatedPath: "data")
            dataItem.loadProductBaseStatus = .succeed
            if favOther?.props != nil {
                if (favOther?.props?.groupProps.count)! > 0 {
                    let dic:WQPropsItem = (favOther?.props!.groupProps[0])!
                    var detailStr = dic.toJSONString()
                    detailStr = detailStr?.replacingOccurrences(of: "{", with: "")
                    detailStr = detailStr?.replacingOccurrences(of: "[", with: "\n")
                    detailStr = detailStr?.replacingOccurrences(of: "]", with: "")
                    detailStr = detailStr?.replacingOccurrences(of: "\"", with: "")
                    detailStr = detailStr?.replacingOccurrences(of: "}", with: "")
                    detailStr = detailStr?.replacingOccurrences(of: ",", with: "\n")
                    item.details = detailStr ?? ""
                }
            }
            dataItem.loadProductBaseStatus = .succeed
            let detailRequestUrl = favOther?.item?.moduleDescUrl
            self.requestProductImages(detailRequestUrl: detailRequestUrl ?? "", index: index)
            self.isloadSucceed()
        }) { (error) in
            dataItem.loadProductBaseStatus = .unLoad
            dataItem.loadProductImagesStatus = .unLoad
            self.isloadSucceed()
        }
        
    }
    
    /// 请求商品的详情页面图片s
    func requestProductImages(detailRequestUrl:String, index:Int) {
        let dataItem = self.dataArray[index]
        if detailRequestUrl == "" {
            dataItem.loadProductImagesStatus = .failed
            self.isloadSucceed()
            return
        }
        var requestUrl = detailRequestUrl
        if (requestUrl.starts(with: "//")) {
            requestUrl = "https:" + requestUrl
            //            print(requestUrl)
            WQRequestHelper.requestOnlyUrl(url: requestUrl, succeed: { (data) in
                let temp = data as! [String:Any]
                let model = WQDetailPictures.deserialize(from: temp, designatedPath: "data")
                var arrayImage:[String] = []
                if model != nil && model!.children.count > 0  {
                    for item in model!.children {
                        let imageUrl = item.params?.picUrl
                        if imageUrl != nil && imageUrl != "" {
                            if ((imageUrl?.starts(with: "//"))!) {
                                arrayImage.append("https:" + imageUrl!)
                            } else {
                                arrayImage.append( imageUrl ?? "")
                            }
                        }
                    }
                }
                dataItem.loadProductImagesStatus = .succeed
                var detailImg = ""
                
                for imgurl in arrayImage {
                    let imgtempt = "<img src=\"\(imgurl)\" alt=\"\(dataItem.title)\"/>"
                    detailImg = detailImg + imgtempt
                }
                if detailImg != "" {
                    let detailT = dataItem.details + "\n"
                    dataItem.details = detailT + detailImg
                }
                
                self.isloadSucceed()
            }){ (error) in
                dataItem.loadProductImagesStatus = .failed
                self.isloadSucceed()
            }
        }
    }
    
    /// 判断是否所有的详情都加载完成
    func isloadSucceed() {
        for item in self.dataArray {
            if item.loadProductBaseStatus == .unLoad  || item.loadProductImagesStatus == .unLoad {
                return
            }
        }
        self.createCSV(array: self.dataArray)
    }
    
    func createCSV(array:[WQFavorites]) -> Void {
        let path:String = self.getfilePath()
        if FileManager.default.fileExists(atPath: path) {
            do {
                try FileManager.default.removeItem(atPath: path)
            } catch {
                print("\(error)")
            }
        }
        let stream = OutputStream(toFileAtPath: path, append: false)!
        let csv = try! CSVWriter(stream: stream)
        
        try! csv.write(row: ["类型","名称","已发布","简短描述","描述","分类","常规售价","促销价格","属性 2 名称","属性 2 值","属性 2 可见","属性 2 的全局","图片","标签"])
        for item in array {
            if item.coupon_remain_count <= 0 {
                continue
            }
            if item.loadProductImagesStatus == .failed || item.loadProductBaseStatus == .failed {
                print("商品：\(item.title)，数据加载不完整不予执行写入命令")
                print("loadProductImagesStatus = \(item.loadProductImagesStatus),loadProductBaseStatus = \(item.loadProductBaseStatus)")
                print("商品ID：\(item.num_iid)，商品链接:\(item.click_url)")
                continue
            }
            let title = item.title
            var urlClick = item.coupon_click_url
            if urlClick == "" {
                urlClick = item.click_url
            }
            let strTime = "优惠券领取时间：\(item.coupon_start_time)-\(item.coupon_end_time)<br>"
            
            let str = "\(strTime)<div class=\"coupon_btn_prod\"><a rel=\"nofollow\" target=\"_blank\" href=\"\(urlClick)\">领优惠券/查看详情</a></div><div style=\"clear: both;\"></div> "
            let shrotDescripe = str
            let descripe = item.details
            //分类判断
            var category:String = self.mtextField.text ?? "其他"
            
            category = categoryFromTitle(title: title, cat: category)
            
            let oldPrice = item.zk_final_price
            var couponPrice:Double = 0.0
            if item.coupon_info.contains("减") {
                let arryTempt = item.coupon_info.components(separatedBy: "减")
                if arryTempt.count == 2 {
                    var stringt = arryTempt[1]
                    stringt = stringt.replacingOccurrences(of: "元", with: "")
                    couponPrice = Double(stringt)!
                } else {
                    print("获取不到优惠券价格")
                    continue
                }
            }
            var price:Double = Double(oldPrice)! - couponPrice
            if price < 0 {
                price = 0
            }
            if price < 10 {
                if price < 4 {
                    category.append(contentsOf: ",一元抢购")
                } else {
                    category.append(contentsOf: ",9.9元包邮")
                }
            }
            let newPrice = "\(price)"
            var pictures = item.pict_url
            let smallImages = item.small_images
            if smallImages != nil {
                
                for (index, pic) in smallImages!.string.enumerated() {
                    if index >= 3 {
                        break;
                    }
                    pictures = pictures + ",\"" + pic
                }
            }
            let attributies2Name = "平台"
            let attributies2Value = "淘宝"
            let tags = "淘宝"
            try! csv.write(row: ["simple", title ,"1",shrotDescripe,descripe,category,oldPrice,newPrice,attributies2Name,attributies2Value,"1","1",pictures,tags])
            //print("商品ID => \(item.num_iid), loadProductImagesStatus => \(item.loadProductImagesStatus) ,loadProductBaseStatus => \(item.loadProductBaseStatus) coupon_infocoup=>\(item.coupon_info) 文件_写入成功")
        }
        csv.stream.close()
        print("全部完成")
        self.shareFile()
    }
    
    func categoryFromTitle(title:String, cat:String) -> String {
        var category = cat
        if(title.contains("护肤品")) {
            if(title.contains("男士")){
                category = "男士护肤";
            } else {
                category = "个妆美护";
            }
        } else if (title.contains("口红")) {
            category = "口红";
        } else if (title.contains("隔离")){
            category = "隔离";
        } else if (title.contains("BB霜") || title.contains("bb霜") || (title.contains("bb") && title.contains("隔离")) ){
            category = "BB霜";
        } else if (title.contains("香水")){
            if(title.contains("男")) {
                category = "男士香水";
            } else {
                category = "女士香水";
            }
        } else if (title.contains("眉笔")){
            category = "眉笔";
        } else if (title.contains("睫毛膏")){
            category = "睫毛膏";
        } else if (title.contains("指甲油")){
            category = "指甲油";
        } else if (title.contains("眼影") || title.contains("眼线")){
            category = "眼影/眼线"
        } else if (title.contains("面部喷雾")) {
            category = "面部喷雾"
        } else if (title.contains("爽肤水")) {
            category = "爽肤水"
        }  else if (title.contains("面膜")) {
            category = "面膜面贴";
        } else if (title.contains("面霜") || title.contains("乳液")) {
            category = "面霜/乳液";
        } else if (title.contains("眼霜") ) {
            category = "眼霜";
        } else if (title.contains("洗发水")) {
            category = "洗发水";
        } else if (title.contains("护发素")) {
            category = "护发素";
        } else if (title.contains("护发精油")) {
            category = "护发精油";
        } else if (title.contains("发膜") || title.contains("染发") || title.contains("假发")) {
            category = "美发护发";
        } else if (title.contains("牙膏")) {
            category = "牙膏";
        } else if(title.contains("牙刷")) {
            category = "牙刷";
            if(title.contains("电动")) {
                category = "电动牙刷";
            }
        } else if (title.contains("漱口水")) {
            category = "漱口水";
        } else if (title.contains("隐形眼镜") || title.contains("眼睛") || title.contains("眼部") ) {
            category = "眼睛护理";
        } else if(title.contains("卫衣")){
            if(title.contains("男")) {
                category = "男士卫衣";
            } else {
                category = "女士卫衣";
            }
        } else if(title.contains("衬衫")){
            if(title.contains("男")) {
                category = "男士衬衫";
            } else {
                category = "女士衬衫";
            }
        } else if(title.contains("外套")){
            if(title.contains("男")) {
                category = "男士外套";
            } else {
                category = "女士外套";
            }
        } else if(title.contains("毛衣")){
            if(title.contains("男")) {
                category = "男士毛衣";
            } else {
                category = "女士毛衣";
            }
        } else if(title.contains("短裤")){
            if(title.contains("男")) {
                category = "男士短裤";
            } else {
                category = "女士短裤";
            }
        } else if(title.contains("休闲裤")){
            if(title.contains("男")) {
                category = "男士休闲裤";
            } else {
                category = "女士休闲裤";
            }
        } else if(title.contains("牛仔裤")){
            if(title.contains("男")) {
                category = "男士牛仔裤";
            } else {
                category = "女士牛仔裤";
            }
        } else if(title.contains("棉服")){
            if(title.contains("男")) {
                category = "男士棉服";
            } else {
                category = "女士棉服";
            }
        } else if(title.contains("T恤") || title.contains("t恤")){
            if(title.contains("男")) {
                category = "男士T恤";
            } else {
                category = "女士T恤";
            }
        } else if(title.contains("毛呢大衣")){
            if(title.contains("男")) {
                category = "男士毛呢大衣";
            } else {
                category = "女士毛呢大衣";
            }
        }
        else if(title.contains("连衣裙")){
            category = "连衣裙";
        } else if(title.contains("半身裙")){
            category = "半身裙";
        } else if(title.contains("包臀裙")){
            category = "包臀裙";
        } else if(title.contains("a字裙")){
            category = "a字裙";
        } else if(title.contains("项链")) {
            category = "项链";
        } else if(title.contains("戒指")) {
            category = "戒指";
        } else if(title.contains("手镯") || title.contains("手链")) {
            category = "手镯/链";
        } else if(title.contains("耳钉") || title.contains("耳环")) {
            category = "耳饰";
        }  else if(title.contains("胸针") || title.contains("挂件") || title.contains("吊坠")) {
            category = "珠宝配饰";
        }
//            文胸 光面文胸美背文胸
        
        else if (title.contains("内裤") || title.contains("内衣")) {
            if (title.contains("男")){
                category = "男士内衣";
            } else {
                category = "女士内衣";
            }
        } else if (title.contains("文胸")) {
            category = "性感文胸";// 聚拢文胸
            if (title.contains("运动")){
               category = "运动文胸";
            } else if (title.contains("无钢圈") || title.contains("无痕")){
               category = "无痕文胸";
            } else if (title.contains("哺乳")){
               category = "哺乳文胸";
            } else if (title.contains("聚拢")){
               category = "聚拢文胸";
            } else if (title.contains("美背")){
               category = "美背文胸";
            }
        } else if (title.contains("家居服")){
           category = "家居服";
        } else if (title.contains("睡衣")) {
            category = "睡衣";
        } else if (title.contains("袜")) {
            category = "袜子";
        } else if (title.contains("情趣内衣")){
           category = "情趣内衣";
        } else if  (title.contains("避孕")) {
            category = "避孕套/药";
        } else if  (title.contains("延时") && title.contains("男")) {
            category = "男用延时";
        } else if (title.contains("震动棒")) {
            category = "震动棒";
        } else if (title.contains("飞机杯")) {
            category = "飞机杯";
        } else if (title.contains("润滑剂")) {
            category = "润滑剂";
        } else if (title.contains("跳弹")) {
            category = "情趣跳弹";
        } else if (title.contains("成人用品") || title.contains("情趣用品")){
            category = "成人用品";
        }
        else if(title.contains("硬盘")) {
            category = "硬盘";
        } else if(title.contains("CPU") || title.contains("cpu")) {
            category = "CPU";
        } else if(title.contains("显卡")) {
            category = "显卡";
        } else if(title.contains("主板")) {
            category = "主板";
        } else if(title.contains("U盘") || title.contains("u盘")) {
            category = "U盘";
        } else if(title.contains("硬盘") || title.contains("移动硬盘")) {
            category = "硬盘";
        } else if(title.contains("机箱")) {
            category = "机箱";
        }
        else if(title.contains("手机")) {
            category = "手机";
            if(title.contains("钢化膜") || title.contains("贴膜") || title.contains("数据线")){
                category = "手机配件";
            }
            if(title.contains("老年")) {
                category = "老年手机";
            }
        }
        else if(title.contains("充电宝")) {
            category = "充电宝";
        }
        else if(title.contains("耳机")) {
            category = "耳机";
        }
        else if(title.contains("电池")) {
            category = "电池";
        }
        else if(title.contains("平板") || title.contains("pad")) {
            category = "平板及配件";
        }
        else if(title.contains("键盘")) {
            category = "键盘";
        }
        else if(title.contains("鼠标")) {
            category = "鼠标";
        }
        else if(title.contains("摄像头")) {
            category = "摄像头";
        }
        else if(title.contains("路由器")) {
            category = "路由器";
        }
        else if(title.contains("音箱")) {
            category = "音箱";
        }
        
        else if (title.contains("电脑")) {
            category = "电脑数码";
            if (title.contains("笔记本电脑")) {
                category = "笔记本电脑";
            } else if (title.contains("台式")) {
                category = "台式电脑";
            } else if (title.contains("DIY电脑") || title.contains("diy电脑")) {
                category = "DIY电脑";
            }
        }
        
        else if(title.contains("电池")) {
            category = "电池";
        }
        else if(title.contains("自拍杆")) {
            category = "自拍杆";
        }
        else if(title.contains("镜头")) {
            category = "镜头";
        }
        else if(title.contains("单反")) {
            category = "单反";
        }
        else if(title.contains("照相机")) {
            category = "照相机";
        }
        else if(title.contains("摄像机")) {
            category = "摄像机";
        }
        else if(title.contains("手环")) {
            category = "智能手环";
        }
        else if (title.contains("VR") || title.contains("vr") || title.contains("AR") || title.contains("ar")) {
            category = "VR/AR";
        }   
        else if (title.contains("休闲食品") || title.contains("零食") || title.contains("坚果") || title.contains("糕点") || title.contains("螺蛳粉")) {
            category = "休闲食品";
        }
        else if  (title.contains("抽纸") || title.contains("卫生纸")) {
             category = "纸品";
         }
        else if  (title.contains("智能") || title.contains("机器人")) {
            category = "智能设备";
        } else if  (title.contains("养生")) {
            category = "养生冲饮";
        }  else if  (title.contains("四件套") || title.contains("枕头") || title.contains("床单")) {
            category = "床上用品";
        }  else if  (title.contains("优酷") || title.contains("芒果tv") || title.contains("爱奇艺") || title.contains("腾讯视频")) {
            category = "影音VIP";
        } else if  (title.contains("洗衣粉") || title.contains("洗衣液")) {
            category = "日用百货";
        } else if(title.contains("礼品")) {
            category = "礼品";
        }
        return category
    }
    
    func getfilePath() -> String {
        let fileName = "/testhu.csv"
        let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        let path:String = paths[0] + fileName
        return path
    }
    
    func shareFile()  {
        let filePath = getfilePath()
        let vc = UIActivityViewController.init(activityItems: [NSURL.init(fileURLWithPath: filePath)], applicationActivities: nil)
        vc.excludedActivityTypes = [.print,.message,.mail,.postToFlickr]
        //显示分享窗口
        self.present(vc, animated: true, completion: nil)
    }
}

// 淘抢购活动列表
//        WQRequestHelper.request(param: ["adzone_id":Adzone_id_6shitu,"fields":"click_url,pic_url,reserve_price,zk_final_price,total_amount,sold_num,title,category_name,start_time,end_time","start_time":"2019-11-13 00:00:00","end_time":"2019-11-14 00:00:00"], method: .get, apiName: request_api_taoqinggou)

/***
 
 "基本信息":
 \n"品牌":"自然婷"
 \n"品名":"故宫口红"
 \n"产地":"中国"
 \n"净含量":"3.5g"
 \n"颜色分类":"801 802 803 804 805 806"
 \n"适合肤质":"任何肤质"
 \n"功效":"持久 提升气色 滋润 自然 水润"
 \n"规格类型":"正常规格"
 \n"是否为特殊用途化妆品":"否"
 \n"限期使用日期范围":"2022-08-08至2022-08-08"
 \n
 \n<img src="https://img.alicdn.com/imgextra/i2/766407860/O1CN01UxsLpL27vveJAfCRy_!!766407860.jpg" />
 <img src="https://img.alicdn.com/imgextra/i2/766407860/O1CN01UxsLpL27vveJAfCRy_!!766407860.jpg" />
 
 */
